package com.campus.counseling.config;

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import java.security.Principal;

@Component
@RequiredArgsConstructor
public class WebSocketEventListener {
    
    // 定义一个日志记录器
    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);
    // 定义一个消息发送操作模板
    private final SimpMessageSendingOperations messagingTemplate;

    // 监听WebSocket连接事件
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        // 记录日志
        logger.info("Received a new web socket connection");
    }

    // 监听WebSocket断开连接事件
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = headerAccessor.getSessionId();
        Principal user = headerAccessor.getUser();
        
        logger.info("WebSocket断开连接 - 会话ID: {}, 用户: {}}", 
            sessionId,
            user != null ? user.getName() : "未知用户"
        );
    }
} 